package com.my.test;

import java.util.Scanner;


//**6.22

public class Estimatesqar {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("请输入n值：");
        long n = input.nextLong();
        System.out.println("n\t\tnextGuess\t\tsqar(n)");
        System.out.println("------------------------------");
        double stimateSqar = Sqarstimate(n);
        double m = Math.sqrt(n);
        System.out.printf("%d\t\t%f\t\t%f\n",n,stimateSqar,m);
    }

    public  static double Sqarstimate(long n){
        if(n == 0){
            return 0;
        }
        if (n < 0){
            System.out.println("n < 0,错误，请重新输入！");
        }
        if (n == 1){
            return 1;
        }
        double lastguess;
        if (n > 1){
            lastguess = n/2.0;
        }else{
            lastguess = 1.0;
        }
        double nextGuess = (lastguess + n / lastguess) / 2;
        while (Math.abs(nextGuess - lastguess) > 0.000001){
            lastguess = nextGuess;
            nextGuess = (lastguess + n / lastguess) / 2;
        }
        return nextGuess;
    }


}
